package com.woniuxy.business.controller;

import com.woniuxy.business.util.WebSocketUtil;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@RestController
@EnableWebSocket//启用websocket
@ServerEndpoint("/business/websocket/{userId}")//作用与requestMapping一样
public class WebSocketHandler {
    @OnOpen
    public void open(@PathParam("userId") String userId, Session session){
        //负责与前端websocket进行连接
        WebSocketUtil.MESSAGEMAP.put(userId,session);
    }

    @OnClose
    public void close(@PathParam("userId") String userId,Session session) throws IOException {
        //前后端断开连接时调用
        WebSocketUtil.MESSAGEMAP.remove(userId);
        //关闭session
        session.close();
    }

    @OnError
    public void onError(Session session,Throwable throwable) {
        //当后台通讯出现异常时调用此方法
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}